/*************************************************************************
 *  Copyright © 2023-2030 FXB CO.,LTD. All rights reserved.
 *------------------------------------------------------------------------
 *  公司：DefaultCompany
 *  项目：CustomBuildProcess
 *  文件：LogInfoHtmlOutput.cs
 *  作者：Administrator
 *  日期：2025/6/14 22:25:27
 *  功能：Nothing
*************************************************************************/

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;
using File = System.IO.File;

namespace CustomBuildProcess.Editor
{
    public class LogInfoHtmlOutput
    {
        public static async Task WriteEncrypBuildLogToHtml(BuildInfo lastBuildInfo, BuildConfigItem logConfigItem)
        {
            string htmlLogPath = PathManager.BuildLogHtmlPath;
            string htmlLogTemplatePath = PathManager.BuildLogHtmlEncryptTemplatePath;
            string LogItemTemplatePath = PathManager.LogItemHtmlTemplatePath;

            try
            {
                string htmlContent;
                if (!File.Exists(htmlLogPath))
                    htmlContent = BuildEncryptHtmlHeader(htmlLogTemplatePath);
                else
                    htmlContent = File.ReadAllText(htmlLogPath);

                // 构建新的日志块
                string newLogBlock = BuildLogHtml(LogItemTemplatePath, lastBuildInfo, logConfigItem);

                // 提取加密数据部分
                int scriptStart = htmlContent.IndexOf("<script id=\"encryptedData\"", StringComparison.Ordinal);
                if (scriptStart >= 0)
                {
                    int contentStart = htmlContent.IndexOf('>', scriptStart) + 1;
                    int contentEnd = htmlContent.IndexOf("</script>", contentStart);

                    string encrypted = htmlContent.Substring(contentStart, contentEnd - contentStart).Trim();

                    // 解密现有内容
                    string decrypted = "";
                    if (!string.IsNullOrEmpty(encrypted))
                        decrypted = AesEncryptor.Decrypt(encrypted);

                    // 插入新日志块到解密后的内容中
                    string h1Tag = $"<div class=\"log-container\"";
                    int h1Index = decrypted.IndexOf(h1Tag, StringComparison.Ordinal);

                    if (h1Index >= 0)
                    {
                        decrypted = decrypted.Insert(h1Index, newLogBlock + "\n");
                    }
                    else
                    {
                        decrypted = newLogBlock;
                    }

                    // 重新加密
                    string encryptedNew = AesEncryptor.Encrypt(decrypted);

                    // 替换 HTML 中的加密内容
                    htmlContent = htmlContent.Substring(0, contentStart) + encryptedNew + htmlContent.Substring(contentEnd);
                }

                // 写回文件
                using (StreamWriter writer = new StreamWriter(htmlLogPath, false, Encoding.UTF8))
                {
                    await writer.WriteAsync(htmlContent);
                }

                //ResetValidToken(htmlLogPath);

                Debug.Log($"Build log appended to HTML at: {htmlLogPath}");
                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogError($"Failed to append HTML build log: {e.Message}");
            }
        }

        public static string BuildEncryptHtmlHeader(string templatePath)
        {
            string htmlTemplate = File.ReadAllText(templatePath);
            htmlTemplate = htmlTemplate.Replace("_BUILDLOGNAME_", $"Build Log")
                                        .Replace("__VALID_USER_PLACEHOLDER__", VersionUtils.ComputeSha256Hash(BuildConfigItem.account))
                                        .Replace("__VALID_PASS_HASH_PLACEHOLDER__", VersionUtils.ComputeSha256Hash(BuildConfigItem.password))
                                        .Replace("__AES_KEY_PLACEHOLDER__", AesEncryptor.Key)
                                        .Replace("__AES_IV_PLACEHOLDER__", AesEncryptor.IV)
                                        .Replace("__ENCRYPTED_CONTENT_PLACEHOLDER__", "")
                                        //这里直接赋值token,不在需要登录
                                        .Replace("__VALID_TOKEN_PLACEHOLDER__", VersionUtils.ComputeSha256Hash(BuildConfigItem.password));
            return htmlTemplate;
        }

        public static void SetValidToken(string htmlPath)
        {
            string htmlContent = File.ReadAllText(htmlPath);
            htmlContent = htmlContent.Replace("__VALID_TOKEN_PLACEHOLDER__", VersionUtils.ComputeSha256Hash(BuildConfigItem.password));
            File.WriteAllText(htmlPath, htmlContent);
        }

        public static void ResetValidToken(string htmlPath)
        {
            string htmlContent = File.ReadAllText(htmlPath);
            string pattern = @"(?<=const\s+validToken\s*=\s*"")[^""]*";
            htmlContent = Regex.Replace(htmlContent, pattern, "__VALID_TOKEN_PLACEHOLDER__");

            File.WriteAllText(htmlPath, htmlContent);
        }

        public static async Task DeleteEncrypBuildLogByVersion(string version, string type)
        {
            string htmlLogPath = PathManager.BuildLogHtmlPath;

            if (!File.Exists(htmlLogPath))
            {
                Debug.Log("The HTML log file does not exist");
                return;
            }

            try
            {
                string htmlContent = File.ReadAllText(htmlLogPath);

                // 查找加密内容区域
                int scriptStart = htmlContent.IndexOf("<script id=\"encryptedData\"", StringComparison.Ordinal);
                if (scriptStart >= 0)
                {
                    int contentStart = htmlContent.IndexOf('>', scriptStart) + 1;
                    int contentEnd = htmlContent.IndexOf("</script>", contentStart);
                    string encrypted = htmlContent.Substring(contentStart, contentEnd - contentStart).Trim();

                    // 解密内容
                    string decrypted = AesEncryptor.Decrypt(encrypted);

                    // 删除指定版本的日志块
                    string pattern = $"<div class=\"log-container\" data-version=\"{Regex.Escape(version)}\" data-type=\"{Regex.Escape(type)}\">[\\s\\S]*?</div>[\\r\\n\\s]*<hr */*>";
                    Regex regex = new Regex(pattern, RegexOptions.Multiline);

                    if (!regex.IsMatch(decrypted))
                    {
                        Debug.LogWarning($"Build log with version {version} ({type} not found");
                        return;
                    }

                    decrypted = regex.Replace(decrypted, "");

                    // 重新加密
                    string encryptedNew = AesEncryptor.Encrypt(decrypted);

                    // 替换 HTML 中的加密内容
                    htmlContent = htmlContent.Substring(0, contentStart) + encryptedNew + htmlContent.Substring(contentEnd);

                    // 写回文件
                    using (StreamWriter writer = new StreamWriter(htmlLogPath, false, Encoding.UTF8))
                    {
                        await writer.WriteAsync(htmlContent);
                    }

                    Debug.Log($"The build log for {version} ({type}) has been deleted");
                    AssetDatabase.Refresh();
                }
            }
            catch (Exception e)
            {
                Debug.LogError($"Failed to delete {version} ({type}) build log: {e.Message}");
            }
        }

        public static string BuildLogHtml(string templatePath, BuildInfo lastBuildInfo, BuildConfigItem logConfigItem)
        {
            string htmlTemplate = File.ReadAllText(templatePath);

            htmlTemplate = htmlTemplate.Replace("_DATA-VERSION_", $"{lastBuildInfo.version}");
            htmlTemplate = htmlTemplate.Replace("_DATA_TYPE_", $"{lastBuildInfo.type}");
            htmlTemplate = htmlTemplate.Replace("_BUILDTIME_", $"{lastBuildInfo.buildTime}");
            htmlTemplate = htmlTemplate.Replace("_PLATFORM_", $" {logConfigItem.GetPlatform(lastBuildInfo.platform)}");
            htmlTemplate = htmlTemplate.Replace("_APPID_", $" {lastBuildInfo.appID}");
            htmlTemplate = htmlTemplate.Replace("_FEATURE_", $" {logConfigItem.GetFeature(lastBuildInfo.feature)}");
            htmlTemplate = htmlTemplate.Replace("_MODEL_", $" {logConfigItem.GetModel(lastBuildInfo.model)}");
            htmlTemplate = htmlTemplate.Replace("_LANGUAGE_", $" {logConfigItem.GetLanguage(lastBuildInfo.language)}");
            htmlTemplate = htmlTemplate.Replace("_TYPE_", $" {logConfigItem.GetType(lastBuildInfo.type)}");
            htmlTemplate = htmlTemplate.Replace("_COMPANYNAME_", $" {lastBuildInfo.companyName}");
            htmlTemplate = htmlTemplate.Replace("_SOFTWARENAME_", $" {lastBuildInfo.productName}");
            htmlTemplate = htmlTemplate.Replace("_VERSION_", $" V{lastBuildInfo.version}");
            htmlTemplate = htmlTemplate.Replace("_BUILDLOG_", $"{"\n" + lastBuildInfo.log + "\n"}");

            return htmlTemplate;
        }
    }
}